{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training accuracy is 1.0\n",
      "Test accuracy is 1.0\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "import copy\n",
    "import numpy as np\n",
    "from sklearn import datasets\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "iris = datasets.load_iris()\n",
    "X = iris.data \n",
    "y = iris.target\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X[:100], y[:100], test_size=0.20)\n",
    "\n",
    "reg = LogisticRegression(solver='lbfgs', max_iter=500)\n",
    "reg.fit(X_train, y_train)\n",
    "print(\"Training accuracy is %s\"% reg.score(X_train,y_train))\n",
    "print(\"Test accuracy is %s\"% reg.score(X_test,y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train accuracy is 1.0\n",
      "Test accuracy is 1.0\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from sklearn.metrics import accuracy_score\n",
    "def sigmoid(x):\n",
    "    z = 1 / (1 + np.exp(-x))\n",
    "    return z\n",
    "\n",
    "def add_b(dataMatrix):\n",
    "    dataMatrix = np.column_stack((np.mat(dataMatrix),np.ones(np.shape(dataMatrix)[0])))    \n",
    "    return dataMatrix\n",
    "\n",
    "def LogisticRegression_(x_train,y_train,x_test,y_test,alpha = 0.001 ,maxCycles = 500):\n",
    "    x_train = add_b(x_train)\n",
    "    x_test = add_b(x_test)\n",
    "    y_train = np.mat(y_train).transpose()\n",
    "    y_test = np.mat(y_test).transpose()\n",
    "    m,n = np.shape(x_train)     \n",
    "    weights = np.ones((n,1))\n",
    "    for i in range(0,maxCycles):\n",
    "        h = sigmoid(x_train*weights)\n",
    "        error = y_train - h\n",
    "        weights = weights + alpha * x_train.transpose() * error\n",
    "        \n",
    "    y_pre = sigmoid(np.dot(x_train, weights))\n",
    "    for i in range(len(y_pre)):        \n",
    "        if y_pre[i] > 0.5:\n",
    "            y_pre[i] = 1\n",
    "        else:\n",
    "            y_pre[i] = 0\n",
    "    print(\"Train accuracy is %s\"% (accuracy_score(y_train, y_pre)))\n",
    "    \n",
    "    y_pre = sigmoid(np.dot(x_test, weights))\n",
    "    for i in range(len(y_pre)):        \n",
    "        if y_pre[i] > 0.5:\n",
    "            y_pre[i] = 1\n",
    "        else:\n",
    "            y_pre[i] = 0\n",
    "    print(\"Test accuracy is %s\"% (accuracy_score(y_test, y_pre)))\n",
    "    \n",
    "    return weights\n",
    "\n",
    "weights = LogisticRegression_(X_train, y_train,X_test,y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "original data:  [[4.4 2.9 1.4 0.2]]\n",
      "original label:  0\n",
      "attack data:  [[4.4 2.9 3.4 0.2]]\n",
      "predict label:  1\n"
     ]
    }
   ],
   "source": [
    "import itertools\n",
    "import copy \n",
    "\n",
    "# Attack on LogisticRegression\n",
    "def LogisticRegression_attack(weights, X_predict, y_predict): \n",
    "    X_predict = add_b(X_predict)\n",
    "    m = np.diag([0.5,0.5,0.5,0.5])*4\n",
    "    flag = True\n",
    "    for i in range(1,5):\n",
    "        for ii in list(itertools.combinations([0,1,2,3],i)):\n",
    "            delta = np.zeros(4)\n",
    "            for jj in ii:\n",
    "                delta += m[jj]\n",
    "            delta = np.append(delta, 0.)\n",
    "            \n",
    "            y_pre = sigmoid(np.dot(copy.deepcopy(X_predict)+delta, weights))       \n",
    "            if y_pre > 0.5:\n",
    "                y_pre = 1\n",
    "            else:\n",
    "                y_pre = 0\n",
    "            if y_predict != y_pre:\n",
    "                X_predict += delta\n",
    "                flag = False\n",
    "                break\n",
    "                \n",
    "            y_pre = sigmoid(np.dot(copy.deepcopy(X_predict)-delta, weights))       \n",
    "            if y_pre > 0.5:\n",
    "                y_pre = 1\n",
    "            else:\n",
    "                y_pre = 0\n",
    "            if y_predict != y_pre:\n",
    "                X_predict -= delta\n",
    "                flag = False\n",
    "                break\n",
    "        if not flag:\n",
    "            break\n",
    "    \n",
    "    y_pre = sigmoid(np.dot(X_predict, weights))       \n",
    "    if y_pre > 0.5:\n",
    "        y_pre = 1\n",
    "    else:\n",
    "        y_pre = 0\n",
    "    print('attack data: ', X_predict[0,:-1])\n",
    "    print('predict label: ', y_pre)\n",
    "\n",
    "X_test_ = X_test[0:1]\n",
    "y_test_ = y_test[0]\n",
    "print('original data: ', X_test_)\n",
    "print('original label: ', y_test_)\n",
    "LogisticRegression_attack(weights, X_test_, y_test_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
